"""
   CommandQueue is equivalent to a MVC frameworks routing map, but to a limited extent.
   All CQ cares about is the handler "name".  So something like webmud.handlers.auth becomes
   simple auth.   On import of the Auth handler, it will self-register with the CommandQueue and
   provide a delegation method/function to take over the rest of the process.
   
   Handler contracts.
      Intake:
      Must accept a dictionary, but the only guarantee is that payload[:type] will be
      set.  So it's up to the individual handlers to ensure their payloads are kosher.
      
      Return:
         All handlers will either throw an Exception ( spec pending ) on error OR return a
         dictionary consisting of simplejson parsable elements.
             
      
"""

import logging
log = logging.getLogger(__name__)

from webmud.lib.reloadablehandlers import ReloadableHandlers

import warnings

warnings.warn("Deprecation notice")

class CommandQueue(object):

    
    def __init__(self, title):
        self.title =  title # for debugging purposes only
        self.queue = {}
        self.default = None
        self.errorHandler = None
        
    def defaultErrorHandler(self, _what,  _why):
        #TODO Perhaps this should be rethought out?
        log.error(_what, _why)        
        
    def setDefault(self, handler):
        self.default = handler
    
    def setErrorHandler(self, handler):
        set.errorHandler = handler
        
                
    def register(self, name, handler, reload = False):
        if self.queue.has_key(name):
            log.warning("module already registed %s " % name)            
            del(self.queue[name])
            
        self.queue[name] = handler
        log.debug("Registered %s handler" % name)        
        
        #TODO put a state debug flag check here
        ReloadableHandlers.reloader(handler)        
        
        
    def deregister(self, name):
        if self.queue.has_key(name):
            del(self.queue[name])
        log.debug("Deregister on %s called" % name)        
        
    def process(self, name, payload):
        if self.queue.has_key(name):
            log.debug("CQ.processing call to %s", name)            
            response = self.queue[name](payload)
            log.debug("Response %s " % response)            
            return response
        else:
            #TODO Make a Kill exception that will eventually be wired to bubble upto WMProtocol
            raise Exception("ABORT & KILL connection")
        
  
                


    
    
